package com.example.dma.controller;

import com.example.dma.pojo.request.LoginRequest;
import com.example.dma.pojo.request.RegisterRequest;
import com.example.dma.pojo.User;
import com.example.dma.service.UserService;
import com.example.dma.util.jwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/lrapi")
@CrossOrigin(origins = "http://localhost:5173")
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private jwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody LoginRequest loginRequest) {
        Map<String, Object> response = new HashMap<>();
        boolean isValid = userService.validateUserCredentials(loginRequest.getUsername(), loginRequest.getPassword());
        // 简单的逻辑检查，您可以用数据库验证替代
        if (isValid) {
            User user = userService.getUserByUsername(loginRequest.getUsername());
            String accessToken = jwtUtil.creatAccessToken(user.getUsername(), user.getEmail());
            response.put("status", 200);
            response.put("message", "登录成功");
            Map<String, Object> data = new HashMap<>();
            data.put("accessToken", accessToken);
            data.put("user", user);
            response.put("data", data);
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> error = new HashMap<>();
            error.put("code", "AUTH_001");
            error.put("description", "Invalid username or password");
            response.put("status", HttpStatus.UNAUTHORIZED.value());
            response.put("message", "认证失败，请重新登录");
            response.put("error", error);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<String> enroll(@RequestBody RegisterRequest registerRequest) {
        // 简单的逻辑检查，您可以用数据库验证替代
        boolean isValid = userService.userExists(registerRequest.getUsername());
        if (!isValid) {
//        User user = userRepository.findByUsername(username); // 查找用户
            userService.addUser(new User(registerRequest.getUsername(), registerRequest.getPassword(), registerRequest.getEmail()));
            return ResponseEntity.ok("注册成功！");
        }
        else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名已存在");
        }
    }

}
